from random import randint

import flask, json
from flask import request
from wordcloud import WordCloud
import numpy as np
from PIL import Image
import time
'''
flask： web框架，通过flask提供的装饰器@server.route()将普通函数转换为服务
登录接口，需要传url、username、passwd
'''
# 创建一个服务，把当前这个python文件当做一个服务
app = flask.Flask(__name__)


# server.config['JSON_AS_ASCII'] = False
# @server.route()可以将普通函数转变为服务 生成词云的路径、请求方式
@app.route('/wdimg', methods=['get', 'post'])
def login():
    # 获取通过url请求传参的数据
    text = request.values.get('text')

    if text:
        print(text)
        mask = np.array(Image.open("love_mark.jpg"))
        wcd = WordCloud(background_color=None, repeat=True, max_words=500, height=480, width=854,
                        max_font_size=48, min_font_size=6, font_path="fonts/msyh.ttc", colormap="RdPu", mask=mask,
                        mode="RGBA", color_func = random_color_func)
        wcd.generate(text)
        wcd.to_image()
        nowTime = str(round(time.time() * 1000))

        addName = "analysisImg/wordcloud"+nowTime+".png"
        print(addName)
        wcd.to_file(addName)
        img_stream = return_img_stream(addName)
        resu = {'code': 200, 'data': img_stream, 'message': '成功！'}
        return json.dumps(resu, ensure_ascii=False)
    else:
        resu = {'code': 10001, 'message': '参数不能为空！'}
        return json.dumps(resu, ensure_ascii=False)


def return_img_stream(img_local_path):
    """
    工具函数:
    获取本地图片流
    :param img_local_path:文件单张图片的本地绝对路径
    :return: 图片流
    """
    import base64
    img_stream = ''
    with open(img_local_path, 'rb') as img_f:
        img_stream = img_f.read()
        img_stream = base64.b64encode(img_stream).decode()
    return img_stream

def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
        h = randint(300, 334)
        s = int(100.0 * 255.0 / 255.0)
        l = int(100.0 * float(randint(60, 120)) / 255.0)
        return "hsl({}, {}%, {}%)".format(h, s, l)

if __name__ == '__main__':
    app.run(debug=True, port=5000, host='0.0.0.0')